package com.yyge.common.controller;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.yyge.common.context.AliyunContext;
import com.yyge.common.enums.AckCode;
import com.yyge.common.vo.resp.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping(value = "/api")
public class UploadController {
    //使用雪花算法生成文件名
    private Snowflake snowflake= IdUtil.getSnowflake(1,0);
    private static final String URL="http://localhost/imgs/";
    private static final String FILE_FOLDER="d:/imgs/";

    private static final String[] MIMES = {"image/gif","image/jpeg","image/png"};

    @Autowired
    AliyunContext aliyunContext;

 private static final long MAX_SIZE =1024 * 1024 * 2;
    @PostMapping("/upload/image")
    public R uplaod(MultipartFile file) throws IOException {
        //非空验证
        if(file.isEmpty()){
            return R.build(AckCode.FILE_NOT_EXIST);
        }

        //上传类型检测
        boolean flag=false;
        for (String mime : MIMES){
            if (file.getContentType().toLowerCase().contains(mime)) {
                flag=true;
                break;
            }
        }

        if(!flag){
            return R.build(AckCode.UPLOAD_TYPE_ERROR);
        }

        //判断文件大小
        if(file.getSize()> MAX_SIZE){
            //ImgUtil.scale(img)
            return R.build(AckCode.UPLOAD_IMAGE_SIZE_LIMIT);
        }


          //本地上传
          //获取文件名file.getOriginalFilename()
        String filename = file.getOriginalFilename();

        //取出文件后缀
        String suffix = filename.substring(filename.lastIndexOf("."));
        //利用雪花算法得出的文件名
        filename = snowflake.nextIdStr()+suffix;
//        //snowflake
//        //文件转存
//        file.transferTo(new File(FILE_FOLDER,filename));
//
//        //返回访问的路径
//        String path=URL+ filename;

        aliyunLaod(filename,file.getInputStream());
                       //https://tyxy-zyk.oss-cn-beijing.aliyuncs.com/1669629796444803072.png
        String imgUrl="https://tyxy-zyk."+"oss-cn-beijing.aliyuncs.com/"+filename;
        System.out.println("图片地址...");
        System.out.println(imgUrl);
        Map<String,String> data=new HashMap<>();
        data.put("image_url",imgUrl);
       return R.okHasData(data);
    }

    public R aliyunLaod(String name, InputStream stream){
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = aliyunContext.getEndpoint();
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = aliyunContext.getKeyid();
        String accessKeySecret = aliyunContext.getKeysecret();

        // 填写Bucket名称，例如examplebucket。
        String bucketName = aliyunContext.getBucketname();
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = name;
        // 填写本地文件的完整路径，例如D:\\localpath\\examplefile.txt。
        // 如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件。

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName,stream);
            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);

            // 上传文件。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }
}
